package com.scs.application.modules.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.modules.device.entity.DeviceLedger;
import com.scs.application.modules.device.entity.DeviceWork;
import com.scs.application.modules.device.entity.DeviceWorkItem;
import com.scs.application.modules.device.entity.DeviceWorkOffer;
import com.scs.application.modules.device.enums.CheckResult;
import com.scs.application.modules.device.enums.DeviceBusMap;
import com.scs.application.modules.device.mapper.DeviceWorkItemMapper;
import com.scs.application.modules.device.service.DeviceLedgerService;
import com.scs.application.modules.device.service.DeviceWorkItemService;
import com.scs.application.modules.device.service.DeviceWorkOfferService;
import com.scs.application.modules.device.service.DeviceWorkService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  设备工作明细表 服务实现类
 */
@Service
@AllArgsConstructor
public class DeviceWorkItemServiceImpl extends BaseServiceImpl<DeviceWorkItemMapper, DeviceWorkItem> implements DeviceWorkItemService {
    private DeviceLedgerService deviceLedgerService;
    private DeviceWorkService deviceWorkService;
    private DeviceWorkOfferService deviceWorkOfferService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateBatch(Collection<DeviceWorkItem> entityList) {
        DeviceWork deviceWork = deviceWorkService.getById(entityList.stream().findFirst().get().getWorkId());
        BusinessException.throwErrorIf(deviceWork == null, "业务单不存在，请刷新重试");
        DeviceBusMap.DeviceBus deviceBus = DeviceBusMap.getDeviceBus(deviceWork.getBusType());
        // 需要锁定库存的
        if (deviceBus.getFlagLock()) {
            deviceLedgerService.lockBatch(
                    entityList.stream().map(DeviceWorkItem::getLedgerId).collect(Collectors.toList()),
                    StrUtil.format("业务锁定，业务单号: {}，业务日期: {}",deviceWork.getBusKey(), DateUtils.format(deviceWork.getBusDate(),DateUtils.YYYYMMDDHHMMSS_PATTER2))
            );
        }

        // 验收安装，修改对应合同明细的安装数量
//        if (deviceBus.getBusType().equals(DeviceBusMap.DEVICE_PO_ACCEPT)) {
//            Collection<DeviceWorkItem> itemContract = this.listByIds(entityList.stream().map(DeviceWorkItem::getWorkItemId).distinct().collect(Collectors.toList()));
//            if (ObjectUtil.length(itemContract) > 0) {
//                Map<String, List<DeviceWorkItem>> itemById =  entityList.stream().collect(Collectors.groupingBy(DeviceWorkItem::getWorkItemId));
//                int acceptNew;
//                for(DeviceWorkItem item : itemContract) {
//                    acceptNew = item.getDeviceQtyAccept() + itemById.get(item.getId()).stream().mapToInt(DeviceWorkItem::getDeviceQtyAccept).sum();
//                    this.update(Wrappers.<DeviceWorkItem>update().set("device_qty_accept", acceptNew).eq("id",item.getId()));
//                }
//            }
//        }
        return super.saveOrUpdateBatch(entityList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        Collection<DeviceWorkItem> deviceWorkItemList =  this.listByIds(idList);
        if (ObjectUtil.length(deviceWorkItemList) > 0) {
            DeviceWork deviceWork = deviceWorkService.getById(deviceWorkItemList.stream().findFirst().get().getWorkId());
            BusinessException.throwErrorIf(deviceWork == null, "业务单据不存在");
            DeviceBusMap.DeviceBus deviceBus = DeviceBusMap.getDeviceBus(deviceWork.getBusType());
            if (deviceBus.getFlagLock()) {
                deviceLedgerService.unlockBatch(
                        deviceWorkItemList.stream().map(DeviceWorkItem::getLedgerId).collect(Collectors.toList())
                );
            }

            // 验收安装，还原对应合同明细的安装数量
            if (deviceBus.getBusType().equals(DeviceBusMap.DEVICE_PO_ACCEPT)) {
                Collection<DeviceWorkItem> itemContract = this.listByIds(deviceWorkItemList.stream().map(DeviceWorkItem::getWorkItemId).distinct().collect(Collectors.toList()));
                Map<String, List<DeviceWorkItem>> itemById =  deviceWorkItemList.stream().collect(Collectors.groupingBy(DeviceWorkItem::getWorkItemId));
                int acceptNew;
                for(DeviceWorkItem item : itemContract) {
                    acceptNew = item.getDeviceQtyAccept() - itemById.get(item.getId()).stream().mapToInt(DeviceWorkItem::getDeviceQtyAccept).sum();
                    this.update(Wrappers.<DeviceWorkItem>update().set("device_qty_accept", acceptNew).eq("id",item.getId()));
                }
            }

            // 报价时，如果相关设备存在报价明细，不允许删除
            if (deviceBus.getBusType().equals(DeviceBusMap.DEVICE_PO_OFFER)) {
                BusinessException.throwErrorIf(deviceWorkOfferService.count(Wrappers.<DeviceWorkOffer>query().in("work_item_id",idList)) > 0, "存在相关报价明细，不允许删除");
            }
        }

        return super.removeCascadeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(DeviceWorkItem entity) {
        DeviceWork deviceWork = deviceWorkService.getById(entity.getWorkId());
        BusinessException.throwErrorIf(deviceWork == null, "业务单不存在，请刷新重试");
        DeviceBusMap.DeviceBus deviceBus = DeviceBusMap.getDeviceBus(deviceWork.getBusType());
        // 验收安装，修改对应合同明细的安装数量
//        if (deviceBus.getBusType().equals(DeviceBusMap.DEVICE_PO_ACCEPT)) {
//            DeviceWorkItem itemContract = this.getById(entity.getWorkItemId());
//            DeviceWorkItem entityDb = this.getById(entity.getId());
//            BusinessException.throwErrorIf(itemContract == null, "对应合同明细不存在，请刷新重试");
//            int acceptNew = itemContract.getDeviceQtyAccept() + entity.getDeviceQtyAccept() -entityDb.getDeviceQtyAccept();
//            BusinessException.throwErrorIf(acceptNew > itemContract.getDeviceQty(), "验收数量已超过安装数量，请刷新重试");
//            this.update(Wrappers.<DeviceWorkItem>update().set("device_qty_accept", acceptNew).eq("id",itemContract.getId()));
//        }
        return super.saveOrUpdate(entity);
    }

    @Override
    public void addByScanForCheck(DeviceWorkItem workItem) {
        DeviceWorkItem find = this.getOne(Wrappers.<DeviceWorkItem>query()
                .eq("work_id", workItem.getWorkId())
                .eq("device_sn", workItem.getDeviceSn()), false);
        if (find == null) {
            DeviceLedger deviceLedger = deviceLedgerService.getByDeviceSn(workItem.getDeviceSn());
            DeviceWorkItem workItemSave = new DeviceWorkItem();
            if (deviceLedger != null) {
                BeanUtil.copyProperties(deviceLedger,workItemSave);
                workItemSave.setId(null).setGmtCreate(null).setGmtModified(null).setModifier(null).setGmtModified(null);
            }
            workItemSave.setWorkId(workItem.getWorkId()).setDeviceSn(workItem.getDeviceSn()).setCheckResult(CheckResult.many);
            this.save(workItemSave);
            return;
        }

        this.update(Wrappers.<DeviceWorkItem>update()
                .set("check_result",CheckResult.normal)
                .eq("check_result",CheckResult.no)
                .eq("work_id", workItem.getWorkId())
                .eq("device_sn", workItem.getDeviceSn()));

    }
}